import { ENV_INFO } from '@/api/config'

// API监控工具类
export class ApiMonitor {
    private static instance: ApiMonitor
    private requestLogs: Array<{
        timestamp: string
        method: string
        url: string
        type: 'READ' | 'WRITE'
        duration: number
        status: number
        success: boolean
    }> = []

    private constructor() { }

    static getInstance(): ApiMonitor {
        if (!ApiMonitor.instance) {
            ApiMonitor.instance = new ApiMonitor()
        }
        return ApiMonitor.instance
    }

    // 记录请求
    logRequest(method: string, url: string, type: 'READ' | 'WRITE', duration: number, status: number, success: boolean) {
        const log = {
            timestamp: new Date().toISOString(),
            method,
            url,
            type,
            duration,
            status,
            success
        }

        this.requestLogs.push(log)

        // 保持日志数量在合理范围内
        if (this.requestLogs.length > 100) {
            this.requestLogs = this.requestLogs.slice(-50)
        }

        // 开发环境下输出到控制台
        if (ENV_INFO.isDev) {
            console.log(`[${type}] ${method} ${url} - ${duration}ms - ${success ? 'SUCCESS' : 'FAILED'}`)
        }
    }

    // 获取请求统计
    getStats() {
        const total = this.requestLogs.length
        const readCount = this.requestLogs.filter(log => log.type === 'READ').length
        const writeCount = this.requestLogs.filter(log => log.type === 'WRITE').length
        const successCount = this.requestLogs.filter(log => log.success).length
        const avgDuration = this.requestLogs.reduce((sum, log) => sum + log.duration, 0) / total || 0

        return {
            total,
            readCount,
            writeCount,
            successCount,
            failCount: total - successCount,
            successRate: total > 0 ? (successCount / total * 100).toFixed(2) : '0.00',
            avgDuration: avgDuration.toFixed(2)
        }
    }

    // 获取最近的请求日志
    getRecentLogs(count: number = 10) {
        return this.requestLogs.slice(-count)
    }

    // 清空日志
    clearLogs() {
        this.requestLogs = []
    }

    // 导出日志
    exportLogs() {
        return JSON.stringify(this.requestLogs, null, 2)
    }

    // 获取环境信息
    getEnvInfo() {
        return {
            mode: ENV_INFO.mode,
            readUrl: ENV_INFO.readUrl,
            writeUrl: ENV_INFO.writeUrl,
            isDev: ENV_INFO.isDev,
            isProd: ENV_INFO.isProd
        }
    }
}

// 创建全局监控实例
export const apiMonitor = ApiMonitor.getInstance()

// 在开发环境下暴露到全局对象，方便调试
if (ENV_INFO.isDev) {
    (window as any).apiMonitor = apiMonitor
} 